<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
          <el-option
            v-for="option in statusOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="bannerList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="图片" min-width="200" align="center">
        <template slot-scope="scope">
          <div v-if="getImageUrl(scope.row.image)" class="image-preview">
            <el-image
              :src="getImageUrl(scope.row.image)"
              :preview-src-list="[getImageUrl(scope.row.image)]"
              fit="cover"
              class="image-preview__item"
            />
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="链接" prop="link" min-width="200" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link v-if="scope.row.link" :href="scope.row.link" type="primary" target="_blank">{{ scope.row.link }}</el-link>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="120" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sort || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="created_at" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at ? parseTime(scope.row.created_at) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="图片" prop="image">
          <image-upload v-model="form.image" :limit="1" :file-size="5" />
        </el-form-item>
        <el-form-item label="链接" prop="link">
          <el-input v-model="form.link" placeholder="请输入链接地址（可选）" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="option in statusOptions" :key="option.value" :label="option.value">{{ option.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" placeholder="请输入排序值" style="width: 100%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBannerList, addBanner, updateBanner, deleteBanner } from '@/api/api'
import ImageUpload from '@/components/ImageUpload'
import { parseTime } from '@/utils/ruoyi'

export default {
  name: 'Banner',
  components: { ImageUpload },
  data() {
    return {
      loading: false,
      submitLoading: false,
      showSearch: true,
      bannerList: [],
      statusOptions: [
        { label: '启用', value: 1 },
        { label: '禁用', value: 2 }
      ],
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: '',
      open: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      queryParams: {
        page: 1,
        pageSize: 10,
        status: undefined
      },
      form: {
        id: undefined,
        image: '',
        link: '',
        status: 1,
        sort: 0
      },
      rules: {
        image: [
          { required: true, message: '请上传图片', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      // 转换参数名为后端需要的格式
      const params = {
        page: this.queryParams.page,
        pagesize: this.queryParams.pageSize
      }
      if (this.queryParams.status !== undefined && this.queryParams.status !== null && this.queryParams.status !== '') {
        params.status = this.queryParams.status
      }
      getBannerList(params)
        .then(res => {
          const { list, total } = this.normalizeResponse(res)
          this.bannerList = list
          this.total = total || list.length
        })
        .finally(() => {
          this.loading = false
        })
    },
    normalizeResponse(res) {
      if (!res) {
        return { list: [], total: 0 }
      }
      if (Array.isArray(res)) {
        return { list: res, total: res.length }
      }
      if (Array.isArray(res.rows)) {
        return { list: res.rows, total: res.total ?? res.rows.length }
      }
      if (Array.isArray(res.data)) {
        return { list: res.data, total: res.total ?? res.data.length }
      }
      if (res.data && Array.isArray(res.data.records)) {
        return { list: res.data.records, total: res.data.total ?? res.data.records.length }
      }
      if (res.data && Array.isArray(res.data.list)) {
        return { list: res.data.list, total: res.data.total ?? res.data.list.length }
      }
      if (Array.isArray(res.list)) {
        return { list: res.list, total: res.total ?? res.list.length }
      }
      if (Array.isArray(res.records)) {
        return { list: res.records, total: res.total ?? res.records.length }
      }
      return { list: [], total: 0 }
    },
    getImageUrl(url) {
      if (!url) return ''
      if (/^https?:\/\//i.test(url)) {
        return url
      }
      if (this.baseUrl && url.startsWith(this.baseUrl)) {
        return url
      }
      if (this.baseUrl) {
        const prefix = this.baseUrl.endsWith('/') ? this.baseUrl.slice(0, -1) : this.baseUrl
        const path = url.startsWith('/') ? url : `/${url}`
        return `${prefix}${path}`
      }
      return url
    },
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    reset() {
      this.form = {
        id: undefined,
        image: '',
        link: '',
        status: 1,
        sort: 0
      }
      this.resetForm('form')
    },
    cancel() {
      this.open = false
      this.reset()
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增轮播图'
    },
    handleUpdate(row) {
      const targetId = row?.id ?? this.ids[0]
      if (!targetId) {
        this.$modal.msgWarning('请选择要修改的轮播图')
        return
      }
      const record = this.bannerList.find(item => String(item.id) === String(targetId))
      if (!record) {
        this.$modal.msgWarning('未找到对应的轮播图数据')
        return
      }
      this.form = {
        id: record.id,
        image: record.image || '',
        link: record.link || '',
        status: record.status !== undefined ? Number(record.status) : 1,
        sort: record.sort !== undefined ? Number(record.sort) : 0
      }
      this.$nextTick(() => {
        if (this.$refs.form && this.$refs.form.clearValidate) {
          this.$refs.form.clearValidate()
        }
      })
      this.open = true
      this.title = '修改轮播图'
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        this.submitLoading = true
        const payload = {
          ...this.form,
          status: this.form.status !== undefined ? Number(this.form.status) : 1,
          sort: this.form.sort !== undefined ? Number(this.form.sort) : 0
        }
        const request = payload.id ? updateBanner(payload) : addBanner({ ...payload, id: undefined })
        request
          .then(() => {
            this.$modal.msgSuccess(payload.id ? '修改成功' : '新增成功')
            this.open = false
            this.getList()
          })
          .finally(() => {
            this.submitLoading = false
          })
      })
    },
    handleDelete(row) {
      const targetIds = row?.id ? [row.id] : this.ids
      if (!targetIds || targetIds.length === 0) {
        this.$modal.msgWarning('请选择要删除的轮播图')
        return
      }
      this.$modal.confirm('是否确认删除选中的轮播图？').then(() => {
        const deletePromises = targetIds.map(id => {
          const record = this.bannerList.find(item => String(item.id) === String(id))
          if (!record) {
            return Promise.resolve()
          }
          const deleteData = {
            id: record.id,
            image: record.image || '',
            link: record.link || '',
            status: record.status,
            created_at: record.created_at,
            sort: record.sort
          }
          return deleteBanner(deleteData)
        })
        return Promise.all(deletePromises)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = selection.length === 0
    },
    getStatusLabel(value) {
      const target = this.statusOptions.find(item => Number(item.value) === Number(value))
      return target ? target.label : '-'
    },
    getStatusTagType(value) {
      const match = Number(value)
      if (match === 1) {
        return 'success'
      }
      if (match === 0) {
        return 'danger'
      }
      return 'default'
    },
    parseTime
  }
}
</script>

<style scoped lang="scss">
.image-preview {
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-preview__item {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
}
</style>

